<template>
  <div class="upload-info">
    <label>选择图片</label>
    <div>
      <el-upload
        class="upload-pic"
        :action="domain"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove1"
        :data="QiniuData"
        :on-error="uploadError"
        :on-success="uploadSuccess1"
        :before-remove="beforeRemove1"
        :before-upload="beforeAvatarUpload1"
        :limit="30"
        ref="upload"
        accept=".jpg, .jpeg, .png"
        multiple
        :on-exceed="handleExceed"
        :file-list="fileList"
      >
        <el-button size="small" type="primary">选择图片</el-button>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" size="tiny">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>

    </div>


    <br>
    <div>
      请输入标题  <el-input v-model="title" placeholder="请输入标题" style="width: 300px"></el-input>
    </div>
    <br>
    <div>
      <textarea placeholder="请输入详细介绍" v-model="introduce">{{introduce}}</textarea>
    </div>
    <br>
    <div>
      <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
      <el-button type="info" @click="cancel" plain >取消</el-button>
    </div>
  </div>
</template>

<script>
  import md5 from 'js-md5';
  let Base64 = require('js-base64').Base64;
export default {
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      loading: false,
      QiniuData: {
        key: "", //图片名字处理
        token: "" //七牛云token
      },
      domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
      qiniuaddr: "https://supimage.miniprogramhacker.cn", // 七牛云的图片外链地址
      uploadPicUrl: "", //提交到后台图片地址
      fileList: [],
      urlList:[],
      introduce:'',
      title:''
    };
  },
  mounted() {
    this.getQiniuToken()
  },
  methods: {

    // === 移除  ===//
    beforeRemove1(file, fileList) {

      return this.$confirm(`确定移除 ${ file.name }？`);

    },
    handleRemove1(file, fileList) {

      return this.handleRemove(file, fileList, this.urlList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 30 张图片，如需更换，请删除上一张图片在重新选择！`
      );
    },
    // === 上传  ===//
    beforeAvatarUpload1: function (file) {

      var randText = this.randomText(5)
      var timestamp = Date.parse(new Date())
      var baseN = Base64.encode(file.name)
      var mdName = md5(baseN+timestamp+randText)
      var key = 'uploadPic/'+mdName
      this.QiniuData.key = key

      return this.beforeAvatarUpload(file, this.urlList, key)
    },
    uploadSuccess1(response, file, fileList) {
      return this.uploadSuccess(response, file, fileList, this.urlList)

    },
    uploadError(err, file, fileList) {
      this.$message({
        message: "上传出错，请重试！",
        type: "error",
        center: true
      });
    },
    // === 预览  ===//
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 取消
    cancel(){
      return this.$confirm("取消本次操作?").then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.$refs.upload.clearAllFile()
        this.urlList.splice(0,this.urlList.length);
        // this.urlList.re
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })
    },
    //提交数据到后台
    handleSubmit() {

      var urls = new Array()
      for (let i = 0, len = this.urlList.length; i < len; i++) {
        var obj = this.urlList[i]
        urls.push(obj.url)
      }

      this.uploadPicUrl = urls.join(",")

      this.getAxios("boardDetail/insert",{
        boardId:1,
        title:this.title,
        userId:1,
        detail:this.introduce,
        images:this.uploadPicUrl
      }).then(res => {
        let {code, data} = res.data
        if (code == 1){ // 清空表单数据
          this.title = ''
          this.introduce = ''
          this.$refs.upload.clearAllFile()
          this.urlList.splice(0,this.urlList.length);
        }
      }).catch(er =>{
        alert('error')
      })


    },

    //请求后台拿七牛云token
    getQiniuToken() {

      this.getAxios('public/qiniuToken').then(res => {

        this.QiniuData.token = res.data;
      });


    }

  }
};
</script>
